package top.lyc829.zzl_android.ui.index;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.tabs.TabLayout;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.citypicker.CityPicker;
import com.xuexiang.citypicker.adapter.OnLocationListener;
import com.xuexiang.citypicker.adapter.OnPickListener;
import com.xuexiang.citypicker.model.City;
import com.xuexiang.citypicker.model.HotCity;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.actionbar.TitleUtils;
import com.xuexiang.xui.widget.tabbar.EasyIndicator;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;
import com.youth.banner.Banner;
import com.youth.banner.indicator.Indicator;
import com.youth.banner.indicator.RoundLinesIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.util.BannerUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.IndexFragmentBinding;
import top.lyc829.zzl_android.logic.bean.BannerBean;
import top.lyc829.zzl_android.logic.bean.BaseBean;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.LiveEventMsg;
import top.lyc829.zzl_android.logic.service.MsgNumberService;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.index.chooseLocation.ChooseLocationActivity;
import top.lyc829.zzl_android.ui.index.serach.SearchActivity;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.main.MainViewModel;
import top.lyc829.zzl_android.ui.message.MessageActivity;
import top.lyc829.zzl_android.ui.setting.SettingActivity;

public class IndexFragment extends LazyFragment {

    private IndexViewModel mViewModel;
    private MainViewModel mainViewModel;
    private IndexFragmentBinding binding;
    BaseAdapter baseAdapter;
    Banner banner;
    RecyclerViewAdapter adapter;

    PageInfo basePage, internshipPage, educationPage;

    TitleBar.ImageAction messageImage;

    int baseType = 0;

    String location = "";

    Badge badgeView;

    public static IndexFragment newInstance() {
        return new IndexFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        binding = IndexFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(IndexViewModel.class);
        mainViewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);
        TitleBar.ActionList actions = new TitleBar.ActionList();

        messageImage = new TitleBar.ImageAction(R.drawable.ic_baseline_email_24) {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
            }
        };




        actions.add(messageImage);
        actions.add(new TitleBar.ImageAction(R.drawable.ic_baseline_search_24) {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(getActivity(), SearchActivity.class));
            }
        });
        binding.mTitleBarIndex.addActions(actions);

        badgeView = new BadgeView(getContext())
                .bindTarget(binding.mTitleBarIndex.getViewByAction(messageImage))
                .setBadgeGravity(Gravity.TOP | Gravity.END)
                .setExactMode(false)
                .setBadgeBackgroundColor(0xdfFFC364)
                .setGravityOffset(-3, 8, true)
                .setBadgePadding(1, true)
                .setBadgeNumber(0);

        binding.mTitleBarIndex.setLeftImageResource(R.drawable.indicator_dowm);
        binding.mTitleBarIndex.setLeftText("地点");
        binding.mTitleBarIndex.setLeftClickListener(v -> {
            Intent intent = new Intent(getActivity(), ChooseLocationActivity.class);
            startActivityForResult(intent, 1);
        });

        basePage = new PageInfo();


        mViewModel.getBannerList().observe(getViewLifecycleOwner(), bannerBeanList -> {

            List<BannerBean> bannerBeans = new ArrayList<>();

            for (BannerBean bannerItem : bannerBeanList) {
                if (!Utils.isStringEmpty(bannerItem.getImgUrl())) {
                    bannerBeans.add(bannerItem);
                }
            }
            banner.setAdapter(new ImageNetAdapter(bannerBeans));
            banner.getAdapter().setOnBannerListener((data, position) -> {
                int id = ((BannerBean) data).getId();
                Intent intent = new Intent(getActivity(), BaseDetailActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
            });
        });

        // recyclerView适配器
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        binding.indexRecyclerView.setLayoutManager(staggeredGridLayoutManager);
        //baseAdapter = new BaseAdapter(null);
        adapter = new RecyclerViewAdapter();
        adapter.setAnimationEnable(true);   // recyclerview加载动画
        binding.indexRecyclerView.setAdapter(adapter);
        binding.indexRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                staggeredGridLayoutManager.invalidateSpanAssignments();//这行主要解决了当加载更多数据时，底部需要重绘，否则布局可能衔接不上。
            }
        });


        setBanner();
        setIndicator();


        // 通过网络请求到基地后刷新界面
        mViewModel.getBaseList().observe(getViewLifecycleOwner(), baseBeans -> {
            Utils.Sout(baseBeans.toString());
            binding.swipeLayout.setRefreshing(false);
            adapter.getLoadMoreModule().setEnableLoadMore(true);
            if (basePage.isFirstPage()) {
                adapter.setList(baseBeans);
            } else {
                adapter.addData(baseBeans);
            }

            if (baseBeans.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                basePage.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
        });



        // 滚动布局 item的点击事件
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getActivity(), BaseDetailActivity.class);
            // 传入基地id，跳转到基地详情页后获取详细信息。
            int id = adapter.getData().get(position).getId();
            intent.putExtra("id", id);
            startActivity(intent);
        });


        LiveEventBus
                .get("index_refresh", LiveEventMsg.class)
                .observe(this, liveEventMsg -> {
                    location = Utils.getValueFromSp("location");
                    binding.swipeLayout.setRefreshing(true);
                    mViewModel.getBannersFromServer(location);
                    refresh();
                    binding.mTitleBarIndex.setLeftText(location.length() > 0 ? location : "地点");
                });

    }



    @Override
    public void lazyInit() {
        //mViewModel.getBannersFromServer(location);


        //refresh();

        initRefreshLayout();
        initLoadMore();

        msgNumberService();

        location = Utils.getValueFromSp("location");
        Utils.Sout(binding.mTitleBarIndex.getLeftText().getText().toString().trim());

        binding.swipeLayout.setRefreshing(true);
        mViewModel.getBannersFromServer(location);
        refresh();
        binding.mTitleBarIndex.setLeftText(location.length() > 0 ? location : "地点");

    }

    /**
     * 处理获取消息个数的服务
     */
    private void msgNumberService() {
        // 观察消息个数
        mainViewModel.getMsgNumberLiveData().observe(getViewLifecycleOwner(), msgNumberBean -> {
            badgeView.setBadgeNumber(msgNumberBean.getTotalNum());
        });
    }

    /**
     * 初始化加载更多
     */
    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void initRefreshLayout() {
        binding.swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        binding.swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    /**
     * 刷新
     */
    private void refresh() {
        //msgNumberService();
        mainViewModel.updateMsgNumber();
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        // 下拉刷新，需要重置页数
        basePage.reset();
        request();

    }

    private void request() {
        String city = Utils.getValueFromSp("location");
        mViewModel.getBasesFromServer(baseType, basePage.getPage(), city);

    }


    private void setIndicator() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.index_indicator, binding.indexRecyclerView, false);
        EasyIndicator indicator = (EasyIndicator) view;
        indicator.setTabTitles(new String[] {"红色", "实习", "支教"});

        indicator.setOnTabClickListener((title, position) -> {
            baseType = position;
            adapter.setList(null);
            refresh();
        });

        adapter.addHeaderView(indicator);
    }

    private void setBanner() {

        // 滚动到顶部
        binding.indexRecyclerView.scrollToPosition(0);

//        binding.bannerIndex.setDelayTime(5000);
//
//        //方法一：使用自定义图片适配器
//        binding.bannerIndex.setAdapter(new ImageNetAdapter(bannerBeanList));
//        binding.bannerIndex.setIndicator(new RoundLinesIndicator(MyApp.getContext()));
//        binding.bannerIndex.setIndicatorSelectedWidth((int) BannerUtils.dp2px(15));

        View header = LayoutInflater.from(getContext()).inflate(R.layout.banner, binding.indexRecyclerView, false);
        banner = (Banner) header;
        banner.setDelayTime(5000);
        //banner.setAdapter(new ImageNetAdapter(bannerBeanList));
        banner.setAdapter(new ImageNetAdapter(null));
        banner.setIndicator(new RoundLinesIndicator(MyApp.getContext()));
        banner.setIndicatorSelectedWidth((int) BannerUtils.dp2px(15));
        banner.start();

        banner.getAdapter().setOnBannerListener((data, position) -> {
            int id = ((BannerBean) data).getId();
            Intent intent = new Intent(getActivity(), BaseDetailActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
        });

        adapter.addHeaderView(banner);
    }

    @Override
    public void onResume() {
        super.onResume();
        //msgNumberService();
        mainViewModel.updateMsgNumber();
    }

}